#!/usr/bin/env node

/**
 * API文档生成脚本
 * 用于从JSDoc注释中提取API信息并生成OpenAPI规范文档
 */

const fs = require('fs');
const path = require('path');
const glob = require('glob');

// 配置
const config = {
  apiDir: path.join(__dirname, '../pages/api'),
  outputFile: path.join(__dirname, '../docs/api-documentation.json'),
  baseUrl: process.env.API_BASE_URL || 'http://localhost:3010'
};

/**
 * 从JSDoc注释中提取响应信息
 * @param {string} comment JSDoc注释内容
 * @returns {Object|null} 响应对象
 */
function extractResponseSchema(comment, filePath) {
  try {
    // 查找responses部分
    const responsesMatch = comment.match(/responses:[\s\S]*?(?=\*\/|$)/i);
    if (!responsesMatch) {
      return null;
    }
    
    const responsesSection = responsesMatch[0];
    const responses = {};
    
    // 提取200响应描述
    const response200Match = responsesSection.match(/200:[\s\S]*?description:\s*(.+)/i);
    const description200 = response200Match ? response200Match[1].trim() : '成功';
    
    // 根据文件路径生成特定的schema引用
    const apiPath = filePath.replace(/\.js$/, '').replace(/.*\/api\//, '');
    const schemaName = generateSchemaName(apiPath);
    
    responses['200'] = {
      description: description200,
      content: {
        'application/json': {
          schema: {
            $ref: `#/components/schemas/${schemaName}`
          }
        }
      }
    };
    
    // 提取500响应
    const response500Match = responsesSection.match(/500:[\s\S]*?(?=\d{3}:|$)/i);
    if (response500Match) {
      responses['500'] = {
        description: '服务器内部错误',
        content: {
          'application/json': {
            schema: {
              $ref: '#/components/schemas/ErrorResponse'
            }
          }
        }
      };
    }
    
    return responses;
  } catch (error) {
    console.warn('解析响应信息时出错:', error.message);
    return null;
  }
}

function generateSchemaName(apiPath) {
  // 根据文件路径生成对应的schema名称
  
  // 高价值商品模块
  if (apiPath.includes('high-goods/quantity-analysis')) {
    return 'HighGoodsQuantityAnalysisResponse';
  }
  if (apiPath.includes('high-goods/financial-analysis')) {
    return 'HighGoodsFinancialAnalysisResponse';
  }
  if (apiPath.includes('high-goods/unit-analysis')) {
    return 'HighGoodsUnitAnalysisResponse';
  }
  if (apiPath.includes('high-goods/time-analysis')) {
    return 'HighGoodsTimeAnalysisResponse';
  }
  if (apiPath.includes('high-goods/efficiency-analysis')) {
    return 'HighGoodsEfficiencyAnalysisResponse';
  }
  if (apiPath.includes('high-goods/basic-stats')) {
    return 'HighGoodsBasicStatsResponse';
  }
  
  // 房屋管理模块
  if (apiPath.includes('room/practical-analysis')) {
    return 'RoomPracticalAnalysisResponse';
  }
  if (apiPath.includes('room/land-analysis')) {
    return 'RoomLandAnalysisResponse';
  }
  if (apiPath.includes('room/efficiency-analysis')) {
    return 'RoomEfficiencyAnalysisResponse';
  }
  if (apiPath.includes('room/complete-analysis')) {
    return 'RoomCompleteAnalysisResponse';
  }
  if (apiPath.includes('room/comparison-analysis')) {
    return 'RoomComparisonAnalysisResponse';
  }
  if (apiPath.includes('room/calculation-analysis')) {
    return 'RoomCalculationAnalysisResponse';
  }
  if (apiPath.includes('room/basic-stats')) {
    return 'RoomBasicStatsResponse';
  }
  
  // 资产管理模块
  if (apiPath.includes('asset/basic-stats')) {
    return 'AssetBasicStatsResponse';
  }
  if (apiPath.includes('asset/category-stats')) {
    return 'AssetCategoryStatsResponse';
  }
  if (apiPath.includes('asset/financial-analysis')) {
    return 'AssetFinancialAnalysisResponse';
  }
  if (apiPath.includes('asset/time-analysis')) {
    return 'AssetTimeAnalysisResponse';
  }
  if (apiPath.includes('asset/status-analysis')) {
    return 'AssetStatusAnalysisResponse';
  }
  if (apiPath.includes('asset/personnel-stats')) {
    return 'AssetPersonnelStatsResponse';
  }
  if (apiPath.includes('asset/area-analysis')) {
    return 'AssetAreaAnalysisResponse';
  }
  
  // 默认使用通用响应
  return 'ApiResponse';
}

/**
 * 从Swagger注释中提取schema定义
 * @param {string} comment Swagger注释内容
 * @returns {Object|null} schema对象
 */
function extractSchemaFromSwagger(comment) {
  try {
    // 查找responses.200.content.application/json.schema部分
    const responsesMatch = comment.match(/responses:[\s\S]*?(?=\*\/|$)/i);
    if (!responsesMatch) {
      return null;
    }
    
    const responsesSection = responsesMatch[0];
    
    // 查找schema部分
    const schemaMatch = responsesSection.match(/schema:[\s\S]*?(?=500:|\*\/|$)/i);
    if (!schemaMatch) {
      return null;
    }
    
    const schemaSection = schemaMatch[0];
    
    // 将schema部分转换为YAML格式并解析
     function convertToYaml(section) {
       const lines = section.split('\n');
       const yamlLines = [];
       let minIndent = Infinity;
       
       // 首先处理所有行，移除*前缀但保留缩进
       const processedLines = [];
       for (const line of lines) {
         if (!line.trim() || line.trim().startsWith('500:')) continue;
         
         let cleanLine;
         if (line.includes('*')) {
           // 有*前缀的行
           cleanLine = line.replace(/^\s*\*\s?/, '');
         } else {
           // 没有*前缀的行，保留原始缩进
           cleanLine = line;
         }
         
         if (cleanLine.trim()) {
           processedLines.push(cleanLine);
           // 计算最小缩进（排除空行）
           const indent = cleanLine.length - cleanLine.trimStart().length;
           if (indent < minIndent) {
             minIndent = indent;
           }
         }
       }
       
       // 调整缩进，使最小缩进为0
       for (const line of processedLines) {
         if (line.trim()) {
           const adjustedLine = line.substring(minIndent);
           yamlLines.push(adjustedLine);
         }
       }
       
       return yamlLines.join('\n');
     }
    
    // 简单的YAML解析器
    function parseYaml(yamlText) {
      const lines = yamlText.split('\n');
      const result = {};
      const stack = [{ obj: result, indent: -1 }];
      
      for (const line of lines) {
        if (!line.trim()) continue;
        
        const indent = line.length - line.trimStart().length;
        const trimmedLine = line.trim();
        
        // 调整栈到当前缩进级别
        while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
          stack.pop();
        }
        
        const currentObj = stack[stack.length - 1].obj;
        
        if (trimmedLine.includes(':')) {
          const colonIndex = trimmedLine.indexOf(':');
          const key = trimmedLine.substring(0, colonIndex).trim();
          const value = trimmedLine.substring(colonIndex + 1).trim();
          
          if (value) {
            // 有值的属性
            if (value.startsWith('"') && value.endsWith('"')) {
              currentObj[key] = value.slice(1, -1);
            } else if (value === 'true' || value === 'false') {
              currentObj[key] = value === 'true';
            } else if (!isNaN(Number(value)) && value !== '') {
              currentObj[key] = Number(value);
            } else {
              currentObj[key] = value;
            }
          } else {
            // 对象属性
            currentObj[key] = {};
            stack.push({ obj: currentObj[key], indent });
          }
        }
      }
      
      return result;
    }
    
    const yamlText = convertToYaml(schemaSection);
    const parsed = parseYaml(yamlText);
    // 如果解析结果包含schema键，则提取其内容
    return parsed && parsed.schema ? parsed.schema : parsed;
    
  } catch (error) {
    console.warn('解析schema时出错:', error.message);
    return null;
  }
}

/**
 * 从所有接口文件中提取schemas
 * @returns {Object} schemas对象
 */
function extractSchemasFromFiles() {
  const schemas = {
    // 通用错误响应
    ErrorResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 500, description: '错误状态码' },
        message: { type: 'string', example: '服务器内部错误', description: '错误消息' },
        error: { type: 'string', description: '错误详情' }
      },
      required: ['code', 'message']
    }
  };
  
  // 查找所有API文件
  const apiFiles = glob.sync('**/*.js', { cwd: config.apiDir });
  
  for (const file of apiFiles) {
    const filePath = path.join(config.apiDir, file);
    
    try {
      const content = fs.readFileSync(filePath, 'utf8');
      const swaggerRegex = /\/\*\*[\s\S]*?@swagger[\s\S]*?\*\//g;
      const matches = content.match(swaggerRegex);
      
      if (matches && matches.length > 0) {
        const comment = matches[0];
        
        // 生成schema名称
        const apiPath = file.replace(/\.js$/, '').replace(/\\/g, '/');
        const schemaName = generateSchemaName(apiPath);
        
        // 提取schema
        const schema = extractSchemaFromSwagger(comment);
        if (schema && schemaName) {
          schemas[schemaName] = schema;
        }
      }
    } catch (error) {
      console.warn(`处理文件 ${filePath} 时出错:`, error.message);
    }
  }
  
  return schemas;
}

function createDetailedSchemas() {
  const extractedSchemas = extractSchemasFromFiles();
  const fallbackSchemas = createFallbackSchemas();
  
  // 优先使用提取的schemas，fallback schemas作为备用
  const mergedSchemas = { ...fallbackSchemas };
  
  // 使用成功提取的schemas覆盖fallback schemas
  for (const [name, schema] of Object.entries(extractedSchemas)) {
    if (schema && typeof schema === 'object') {
      // 更宽松的条件：只要是对象就使用提取的schema
      mergedSchemas[name] = schema;
      console.log(`✓ 使用提取的schema: ${name}`);
    } else {
      console.log(`⚠ 提取schema失败，使用fallback: ${name}`);
    }
  }
  
  return mergedSchemas;
}

// 保留原有的硬编码schemas作为备用
function createFallbackSchemas() {
  return {
    // 高价值商品相关schemas
    HighGoodsQuantityAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '数量分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            basicStats: {
              type: 'object',
              description: '基础统计信息',
              properties: {
                totalQuantity: { type: 'number', description: '总数量' },
                avgQuantity: { type: 'string', description: '平均数量' },
                maxQuantity: { type: 'number', description: '最大数量' },
                minQuantity: { type: 'number', description: '最小数量' },
                recordCount: { type: 'number', description: '记录数' },
                totalAmount: { type: 'number', description: '总金额' }
              }
            },
            quantityDistribution: {
              type: 'array',
              description: '数量分布统计',
              items: {
                type: 'object',
                properties: {
                  quantityRange: { type: 'string', description: '数量范围' },
                  recordCount: { type: 'number', description: '记录数' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            },
            timeAnalysis: {
              type: 'object',
              description: '时间分析数据',
              properties: {
                totalTimePoints: { type: 'number', description: '总时间点数' },
                timeRange: {
                  type: 'object',
                  properties: {
                    earliest: { type: 'string', description: '最早时间' },
                    latest: { type: 'string', description: '最晚时间' }
                  }
                },
                data: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      range: { type: 'string', description: '数量范围' },
                      count: { type: 'integer', description: '记录数' },
                      percentage: { type: 'number', description: '占比' }
                    }
                  }
                }
              }
            },
            trends: {
              type: 'object',
              description: '趋势分析数据',
              properties: {
                description: { type: 'string', example: '数量趋势分析' },
                data: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      period: { type: 'string', description: '时间周期' },
                      totalQuantity: { type: 'integer', description: '总数量' },
                      avgQuantity: { type: 'number', description: '平均数量' }
                    }
                  }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 高价值商品财务分析
    HighGoodsFinancialAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '财务分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            summary: {
              type: 'object',
              description: '财务汇总信息',
              properties: {
                totalValue: { type: 'number', description: '总价值' },
                avgValue: { type: 'number', description: '平均价值' },
                maxValue: { type: 'number', description: '最大价值' },
                minValue: { type: 'number', description: '最小价值' }
              }
            },
            valueDistribution: {
              type: 'array',
              description: '价值分布统计',
              items: {
                type: 'object',
                properties: {
                  valueRange: { type: 'string', description: '价值范围' },
                  count: { type: 'integer', description: '数量' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            },
            trends: {
              type: 'array',
              description: '价值趋势数据',
              items: {
                type: 'object',
                properties: {
                  period: { type: 'string', description: '时间周期' },
                  totalValue: { type: 'number', description: '总价值' },
                  avgValue: { type: 'number', description: '平均价值' },
                  count: { type: 'integer', description: '数量' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 房屋实用性分析
    RoomPracticalAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '实用性分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            utilizationStats: {
              type: 'object',
              description: '利用率统计',
              properties: {
                avgUtilization: { type: 'string', description: '平均利用率' },
                maxUtilization: { type: 'string', description: '最高利用率' },
                minUtilization: { type: 'string', description: '最低利用率' }
              }
            },
            areaAnalysis: {
              type: 'object',
              description: '面积分析',
              properties: {
                totalArea: { type: 'number', description: '总面积' },
                usedArea: { type: 'number', description: '已使用面积' },
                unusedArea: { type: 'number', description: '未使用面积' }
              }
            },
            spaceConfiguration: {
              type: 'array',
              description: '空间配置信息',
              items: {
                type: 'object',
                properties: {
                  spaceType: { type: 'string', description: '空间类型' },
                  area: { type: 'number', description: '面积' },
                  utilization: { type: 'string', description: '利用率' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 资产基础统计
    AssetBasicStatsResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '基础统计获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            totalAssets: { type: 'integer', description: '资产总数' },
            totalValue: { type: 'number', description: '资产总价值' },
            categoryStats: {
              type: 'array',
              description: '分类统计',
              items: {
                type: 'object',
                properties: {
                  category: { type: 'string', description: '资产类别' },
                  count: { type: 'integer', description: '数量' },
                  value: { type: 'number', description: '价值' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            },
            statusDistribution: {
              type: 'array',
              description: '状态分布',
              items: {
                type: 'object',
                properties: {
                  status: { type: 'string', description: '资产状态' },
                  count: { type: 'integer', description: '数量' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 高价值商品单位分析
    HighGoodsUnitAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '单位分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            quantityRanking: {
              type: 'object',
              description: '数量排行榜',
              properties: {
                description: { type: 'string', example: '单位高价值品数量排行榜（Top 20）' },
                data: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      rank: { type: 'integer', description: '排名' },
                      unitName: { type: 'string', description: '单位名称' },
                      totalQuantity: { type: 'integer', description: '总数量' },
                      percentage: { type: 'string', description: '占比' }
                    }
                  }
                }
              }
            },
            amountRanking: {
              type: 'object',
              description: '金额排行榜',
              properties: {
                description: { type: 'string', example: '单位高价值品金额排行榜（Top 20）' },
                data: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      rank: { type: 'integer', description: '排名' },
                      unitName: { type: 'string', description: '单位名称' },
                      totalAmount: { type: 'number', description: '总金额' },
                      percentage: { type: 'string', description: '占比' }
                    }
                  }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 高价值商品时间分析
    HighGoodsTimeAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '时间分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            timeDistribution: {
              type: 'object',
              description: '时间分布统计',
              properties: {
                description: { type: 'string', example: '高价值品时间分布' },
                data: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      period: { type: 'string', description: '时间周期' },
                      count: { type: 'integer', description: '数量' },
                      amount: { type: 'number', description: '金额' }
                    }
                  }
                }
              }
            },
            trends: {
              type: 'object',
              description: '趋势分析',
              properties: {
                description: { type: 'string', example: '时间趋势分析' },
                data: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      year: { type: 'string', description: '年份' },
                      totalQuantity: { type: 'integer', description: '总数量' },
                      totalAmount: { type: 'number', description: '总金额' },
                      growth: { type: 'string', description: '增长率' }
                    }
                  }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 房屋土地分析
    RoomLandAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '土地分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            officeLandInfo: {
              type: 'object',
              description: '办公用房土地信息',
              properties: {
                acres: { type: 'number', description: '办公用房土地面积（亩）' },
                squareMeters: { type: 'string', description: '办公用房土地面积（平方米）' },
                description: { type: 'string', description: '土地描述' }
              }
            },
            totalLandInfo: {
              type: 'object',
              description: '总土地信息',
              properties: {
                acres: { type: 'number', description: '总土地面积（亩）' },
                squareMeters: { type: 'string', description: '总土地面积（平方米）' },
                description: { type: 'string', description: '土地描述' }
              }
            },
            buildingDensity: {
              type: 'object',
              description: '建筑密度分析',
              properties: {
                density: { type: 'string', description: '建筑密度' },
                utilization: { type: 'string', description: '土地利用率' }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 资产分类统计
    AssetCategoryStatsResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '分类统计获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            categoryOverview: {
              type: 'object',
              description: '分类概览',
              properties: {
                description: { type: 'string', example: '分类概览' },
                data: {
                  type: 'object',
                  properties: {
                    totalCategories: { type: 'integer', description: '总分类数' },
                    totalAssets: { type: 'integer', description: '总资产数' },
                    totalValue: { type: 'number', description: '总价值' }
                  }
                }
              }
            },
            categoryDetails: {
              type: 'array',
              description: '分类详情',
              items: {
                type: 'object',
                properties: {
                  categoryName: { type: 'string', description: '分类名称' },
                  count: { type: 'integer', description: '数量' },
                  value: { type: 'number', description: '价值' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            },
            topCategories: {
              type: 'array',
              description: 'Top分类排行',
              items: {
                type: 'object',
                properties: {
                  rank: { type: 'integer', description: '排名' },
                  categoryName: { type: 'string', description: '分类名称' },
                  count: { type: 'integer', description: '数量' },
                  value: { type: 'number', description: '价值' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 资产财务分析
    AssetFinancialAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '财务分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            financialSummary: {
              type: 'object',
              description: '财务汇总',
              properties: {
                totalInvestment: { type: 'number', description: '总投资' },
                totalValue: { type: 'number', description: '总价值' },
                roi: { type: 'string', description: '投资回报率' },
                avgCost: { type: 'number', description: '平均成本' }
              }
            },
            costAnalysis: {
              type: 'array',
              description: '成本分析',
              items: {
                type: 'object',
                properties: {
                  category: { type: 'string', description: '类别' },
                  cost: { type: 'number', description: '成本' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            },
            trends: {
              type: 'array',
              description: '财务趋势',
              items: {
                type: 'object',
                properties: {
                  period: { type: 'string', description: '时间周期' },
                  investment: { type: 'number', description: '投资额' },
                  value: { type: 'number', description: '价值' },
                  growth: { type: 'string', description: '增长率' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 资产时间分析
    AssetTimeAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '时间分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            timeDistribution: {
              type: 'array',
              description: '时间分布',
              items: {
                type: 'object',
                properties: {
                  period: { type: 'string', description: '时间周期' },
                  count: { type: 'integer', description: '数量' },
                  value: { type: 'number', description: '价值' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            },
            trends: {
              type: 'array',
              description: '趋势分析',
              items: {
                type: 'object',
                properties: {
                  date: { type: 'string', description: '日期' },
                  acquisitions: { type: 'integer', description: '新增资产数' },
                  disposals: { type: 'integer', description: '处置资产数' },
                  netChange: { type: 'integer', description: '净变化' }
                }
              }
            },
            summary: {
              type: 'object',
              description: '时间分析汇总',
              properties: {
                totalPeriods: { type: 'integer', description: '总时间周期数' },
                avgGrowthRate: { type: 'string', description: '平均增长率' },
                peakPeriod: { type: 'string', description: '峰值周期' }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 资产状态分析
    AssetStatusAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '状态分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            statusDistribution: {
              type: 'array',
              description: '状态分布',
              items: {
                type: 'object',
                properties: {
                  status: { type: 'string', description: '状态' },
                  count: { type: 'integer', description: '数量' },
                  percentage: { type: 'string', description: '占比' },
                  value: { type: 'number', description: '价值' }
                }
              }
            },
            statusTrends: {
              type: 'array',
              description: '状态趋势',
              items: {
                type: 'object',
                properties: {
                  period: { type: 'string', description: '时间周期' },
                  active: { type: 'integer', description: '在用数量' },
                  idle: { type: 'integer', description: '闲置数量' },
                  maintenance: { type: 'integer', description: '维修数量' },
                  disposed: { type: 'integer', description: '处置数量' }
                }
              }
            },
            healthScore: {
              type: 'object',
              description: '资产健康度评分',
              properties: {
                overall: { type: 'number', description: '总体评分' },
                utilization: { type: 'number', description: '利用率评分' },
                maintenance: { type: 'number', description: '维护评分' },
                efficiency: { type: 'number', description: '效率评分' }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 资产人员统计
    AssetPersonnelStatsResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '人员统计获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            personnelOverview: {
              type: 'object',
              description: '人员概览',
              properties: {
                totalPersonnel: { type: 'integer', description: '总人员数' },
                activeUsers: { type: 'integer', description: '活跃用户数' },
                avgAssetsPerPerson: { type: 'number', description: '人均资产数' },
                utilizationRate: { type: 'string', description: '利用率' }
              }
            },
            departmentStats: {
              type: 'array',
              description: '部门统计',
              items: {
                type: 'object',
                properties: {
                  department: { type: 'string', description: '部门名称' },
                  personnelCount: { type: 'integer', description: '人员数量' },
                  assetCount: { type: 'integer', description: '资产数量' },
                  avgValue: { type: 'number', description: '平均价值' }
                }
              }
            },
            topUsers: {
              type: 'array',
              description: 'Top用户排行',
              items: {
                type: 'object',
                properties: {
                  rank: { type: 'integer', description: '排名' },
                  userName: { type: 'string', description: '用户名' },
                  department: { type: 'string', description: '部门' },
                  assetCount: { type: 'integer', description: '资产数量' },
                  totalValue: { type: 'number', description: '总价值' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 资产区域分析
    AssetAreaAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '区域分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            areaDistribution: {
              type: 'array',
              description: '区域分布',
              items: {
                type: 'object',
                properties: {
                  area: { type: 'string', description: '区域名称' },
                  count: { type: 'integer', description: '资产数量' },
                  value: { type: 'number', description: '总价值' },
                  percentage: { type: 'string', description: '占比' },
                  density: { type: 'string', description: '密度' }
                }
              }
            },
            areaComparison: {
              type: 'array',
              description: '区域对比',
              items: {
                type: 'object',
                properties: {
                  area: { type: 'string', description: '区域名称' },
                  efficiency: { type: 'number', description: '效率指数' },
                  utilization: { type: 'string', description: '利用率' },
                  growth: { type: 'string', description: '增长率' }
                }
              }
            },
            hotspots: {
              type: 'array',
              description: '热点区域',
              items: {
                type: 'object',
                properties: {
                  rank: { type: 'integer', description: '排名' },
                  area: { type: 'string', description: '区域名称' },
                  score: { type: 'number', description: '热度评分' },
                  reason: { type: 'string', description: '热点原因' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 房屋完整分析
    RoomCompleteAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '完整分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            basicStats: {
              type: 'object',
              description: '基础统计信息',
              properties: {
                rooms: {
                  type: 'object',
                  properties: {
                    totalRooms: { type: 'integer', example: 1250, description: '总房间数' },
                    publicRooms: { type: 'integer', example: 280, description: '公共房间数' },
                    privateRooms: { type: 'integer', example: 970, description: '私人房间数' },
                    publicRoomRatio: { type: 'string', example: '22.40', description: '公共房间比例' }
                  }
                },
                buildings: {
                  type: 'object',
                  properties: {
                    totalBuildings: { type: 'integer', example: 45, description: '总建筑数' },
                    avgRoomsPerBuilding: { type: 'string', example: '27.78', description: '平均每栋建筑房间数' }
                  }
                },
                areas: {
                  type: 'object',
                  properties: {
                    totalBuildingArea: { type: 'string', example: '125000.50', description: '总建筑面积' },
                    totalUsageArea: { type: 'string', example: '98500.25', description: '总使用面积' },
                    totalConstructionArea: { type: 'string', example: '120333.35', description: '总建设面积' },
                    usageRate: { type: 'string', example: '78.80', description: '使用率' }
                  }
                },
                land: {
                  type: 'object',
                  properties: {
                    totalLandAreaMu: { type: 'string', example: '180.50', description: '总土地面积(亩)' },
                    officeLandAreaMu: { type: 'string', example: '150.25', description: '办公用地面积(亩)' },
                    totalLandAreaSqm: { type: 'string', example: '120333.35', description: '总土地面积(平方米)' }
                  }
                }
              }
            },
            efficiencyMetrics: {
              type: 'object',
              description: '效率指标',
              properties: {
                spaceUtilization: {
                  type: 'object',
                  properties: {
                    buildingToUsageRatio: { type: 'string', example: '78.80', description: '建筑使用率' },
                    level: { type: 'string', example: '良好', description: '效率等级' }
                  }
                },
                roomEfficiency: {
                  type: 'object',
                  properties: {
                    averageAreaPerRoom: { type: 'string', example: '78.80', description: '平均房间面积' },
                    roomsPerSquareMeter: { type: 'string', example: '0.010000', description: '每平方米房间数' }
                  }
                },
                landEfficiency: {
                  type: 'object',
                  properties: {
                    buildingDensity: { type: 'string', example: '103.85', description: '建筑密度' },
                    floorAreaRatio: { type: 'string', example: '1.12', description: '容积率' },
                    roomsPerAcre: { type: 'string', example: '6.92', description: '每亩房间数' }
                  }
                }
              }
            },
            comparativeAnalysis: {
              type: 'object',
              description: '对比分析',
              properties: {
                areaComparison: {
                  type: 'object',
                  properties: {
                    buildingToLandRatio: { type: 'string', example: '0.0086', description: '建筑与土地面积比' },
                    usageToLandRatio: { type: 'string', example: '0.0068', description: '使用与土地面积比' }
                  }
                },
                roomComparison: {
                  type: 'object',
                  properties: {
                    publicToPrivateRatio: { type: 'string', example: '0.1429', description: '公共与私人房间比' },
                    roomDensityPerBuilding: { type: 'string', example: '7.00', description: '每栋建筑房间密度' }
                  }
                }
              }
            },
            developmentPotential: {
              type: 'object',
              description: '发展潜力',
              properties: {
                floorAreaRatio: { type: 'string', example: '1.12', description: '容积率' },
                buildingDensity: { type: 'string', example: '103.85', description: '建筑密度' },
                expansionCapacity: { type: 'string', example: '中等', description: '扩展能力' },
                potentialNewRooms: { type: 'string', example: '15', description: '潜在新增房间数' }
              }
            },
            overallAssessment: {
              type: 'object',
              description: '综合评估',
              properties: {
                scores: {
                  type: 'object',
                  properties: {
                    spaceUtilization: { type: 'string', example: '78', description: '空间利用率评分' },
                    landUtilization: { type: 'string', example: '85', description: '土地利用率评分' },
                    roomConfiguration: { type: 'string', example: '72', description: '房间配置评分' },
                    buildingEfficiency: { type: 'string', example: '80', description: '建筑效率评分' }
                  }
                },
                overallRating: { type: 'string', example: 'B级-良好', description: '综合评级' }
              }
            },
            recommendations: {
              type: 'object',
              description: '建议',
              properties: {
                immediate: {
                  type: 'array',
                  items: { type: 'string' },
                  example: ['优化空间布局，提高使用效率', '加强房间功能配置'],
                  description: '即时建议'
                },
                longTerm: {
                  type: 'array',
                  items: { type: 'string' },
                  example: ['考虑扩建以提高容积率', '规划新的建筑项目'],
                  description: '长期建议'
                },
                specific: {
                  type: 'array',
                  items: { type: 'string' },
                  example: ['在现有土地上可新增约150个房间', '建议提升建筑密度至120'],
                  description: '具体建议'
                }
              }
            },
            summary: {
              type: 'object',
              description: '摘要',
              properties: {
                dataCompleteness: { type: 'string', example: '95%', description: '数据完整性' },
                keyHighlights: {
                  type: 'array',
                  items: { type: 'string' },
                  example: ['土地利用率较高(85分)', '房间配置合理(90分)', '仍有发展潜力'],
                  description: '关键亮点'
                },
                analysisDate: { type: 'string', example: '2024-01-25', description: '分析日期' }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 房屋对比分析
    RoomComparisonAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '对比分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            comparisonResults: {
              type: 'array',
              description: '对比结果',
              items: {
                type: 'object',
                properties: {
                  category: { type: 'string', description: '对比类别' },
                  current: { type: 'number', description: '当前值' },
                  previous: { type: 'number', description: '对比值' },
                  change: { type: 'string', description: '变化' },
                  changeRate: { type: 'string', description: '变化率' }
                }
              }
            },
            benchmarks: {
              type: 'object',
              description: '基准对比',
              properties: {
                industryAvg: { type: 'number', description: '行业平均' },
                currentValue: { type: 'number', description: '当前值' },
                performance: { type: 'string', description: '表现评级' }
              }
            },
            recommendations: {
              type: 'array',
              description: '改进建议',
              items: {
                type: 'object',
                properties: {
                  area: { type: 'string', description: '改进领域' },
                  suggestion: { type: 'string', description: '具体建议' },
                  priority: { type: 'string', description: '优先级' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 房屋计算分析
    RoomCalculationAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '计算分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            calculations: {
              type: 'object',
              description: '计算结果',
              properties: {
                totalArea: { type: 'number', description: '总面积计算' },
                usableArea: { type: 'number', description: '可用面积' },
                efficiency: { type: 'string', description: '空间效率' },
                costPerSqm: { type: 'number', description: '每平米成本' }
              }
            },
            formulas: {
              type: 'array',
              description: '计算公式',
              items: {
                type: 'object',
                properties: {
                  name: { type: 'string', description: '公式名称' },
                  formula: { type: 'string', description: '计算公式' },
                  result: { type: 'number', description: '计算结果' },
                  unit: { type: 'string', description: '单位' }
                }
              }
            },
            projections: {
              type: 'array',
              description: '预测数据',
              items: {
                type: 'object',
                properties: {
                  period: { type: 'string', description: '预测周期' },
                  projected: { type: 'number', description: '预测值' },
                  confidence: { type: 'string', description: '置信度' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 房屋基础统计
    RoomBasicStatsResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '基础统计获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            summary: {
              type: 'object',
              description: '统计汇总',
              properties: {
                totalCount: { type: 'integer', description: '总数量' },
                totalArea: { type: 'number', description: '总面积' },
                avgArea: { type: 'number', description: '平均面积' },
                occupancyRate: { type: 'string', description: '占用率' }
              }
            },
            distribution: {
              type: 'array',
              description: '分布统计',
              items: {
                type: 'object',
                properties: {
                  category: { type: 'string', description: '分类' },
                  count: { type: 'integer', description: '数量' },
                  area: { type: 'number', description: '面积' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            },
            topRooms: {
              type: 'array',
              description: 'Top房间排行',
              items: {
                type: 'object',
                properties: {
                  rank: { type: 'integer', description: '排名' },
                  roomId: { type: 'string', description: '房间ID' },
                  area: { type: 'number', description: '面积' },
                  type: { type: 'string', description: '类型' },
                  utilization: { type: 'string', description: '利用率' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 高价值商品基础统计
    HighGoodsBasicStatsResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '基础统计获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            overview: {
              type: 'object',
              description: '统计概览',
              properties: {
                totalItems: { type: 'integer', description: '总商品数量' },
                totalValue: { type: 'number', description: '总价值' },
                avgValue: { type: 'number', description: '平均价值' },
                highValueThreshold: { type: 'number', description: '高价值阈值' }
              }
            },
            categoryStats: {
              type: 'array',
              description: '分类统计',
              items: {
                type: 'object',
                properties: {
                  category: { type: 'string', description: '商品类别' },
                  count: { type: 'integer', description: '数量' },
                  totalValue: { type: 'number', description: '总价值' },
                  avgValue: { type: 'number', description: '平均价值' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            },
            valueDistribution: {
              type: 'array',
              description: '价值分布',
              items: {
                type: 'object',
                properties: {
                  range: { type: 'string', description: '价值范围' },
                  count: { type: 'integer', description: '数量' },
                  percentage: { type: 'string', description: '占比' }
                }
              }
            },
            topItems: {
              type: 'array',
              description: 'Top商品排行',
              items: {
                type: 'object',
                properties: {
                  rank: { type: 'integer', description: '排名' },
                  itemName: { type: 'string', description: '商品名称' },
                  category: { type: 'string', description: '类别' },
                  value: { type: 'number', description: '价值' },
                  quantity: { type: 'integer', description: '数量' }
                }
              }
            },
            trends: {
              type: 'object',
              description: '趋势指标',
              properties: {
                monthlyGrowth: { type: 'string', description: '月增长率' },
                yearlyGrowth: { type: 'string', description: '年增长率' },
                volatility: { type: 'string', description: '波动性' }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 高价值商品效率分析
    HighGoodsEfficiencyAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '效率分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            efficiencyOverview: {
              type: 'object',
              description: '效率概览',
              properties: {
                overallEfficiency: { type: 'string', description: '总体效率' },
                utilizationRate: { type: 'string', description: '利用率' },
                turnoverRate: { type: 'string', description: '周转率' },
                performanceScore: { type: 'number', description: '绩效评分' }
              }
            },
            categoryEfficiency: {
              type: 'array',
              description: '分类效率',
              items: {
                type: 'object',
                properties: {
                  category: { type: 'string', description: '商品类别' },
                  efficiency: { type: 'string', description: '效率指标' },
                  utilization: { type: 'string', description: '利用率' },
                  ranking: { type: 'integer', description: '排名' }
                }
              }
            },
            trends: {
              type: 'array',
              description: '效率趋势',
              items: {
                type: 'object',
                properties: {
                  period: { type: 'string', description: '时间周期' },
                  efficiency: { type: 'string', description: '效率值' },
                  change: { type: 'string', description: '变化幅度' },
                  trend: { type: 'string', description: '趋势方向' }
                }
              }
            },
            recommendations: {
              type: 'array',
              description: '效率优化建议',
              items: {
                type: 'object',
                properties: {
                  area: { type: 'string', description: '优化领域' },
                  suggestion: { type: 'string', description: '具体建议' },
                  impact: { type: 'string', description: '预期影响' },
                  priority: { type: 'string', description: '优先级' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 房屋效率分析
    RoomEfficiencyAnalysisResponse: {
      type: 'object',
      properties: {
        code: { type: 'integer', example: 200, description: '响应状态码' },
        message: { type: 'string', example: '效率分析获取成功', description: '响应消息' },
        data: {
          type: 'object',
          properties: {
            spaceEfficiency: {
              type: 'object',
              description: '空间效率',
              properties: {
                utilizationRate: { type: 'string', description: '空间利用率' },
                occupancyRate: { type: 'string', description: '占用率' },
                efficiency: { type: 'string', description: '效率评级' },
                wasteRate: { type: 'string', description: '浪费率' }
              }
            },
            roomTypeEfficiency: {
              type: 'array',
              description: '房间类型效率',
              items: {
                type: 'object',
                properties: {
                  roomType: { type: 'string', description: '房间类型' },
                  efficiency: { type: 'string', description: '效率指标' },
                  utilization: { type: 'string', description: '利用率' },
                  performance: { type: 'string', description: '性能评级' }
                }
              }
            },
            costEfficiency: {
              type: 'object',
              description: '成本效率',
              properties: {
                costPerSqm: { type: 'number', description: '每平米成本' },
                roi: { type: 'string', description: '投资回报率' },
                maintenanceCost: { type: 'number', description: '维护成本' },
                efficiency: { type: 'string', description: '成本效率' }
              }
            },
            improvements: {
              type: 'array',
              description: '改进建议',
              items: {
                type: 'object',
                properties: {
                  area: { type: 'string', description: '改进区域' },
                  currentState: { type: 'string', description: '当前状态' },
                  targetState: { type: 'string', description: '目标状态' },
                  actions: { type: 'string', description: '改进措施' },
                  expectedGain: { type: 'string', description: '预期收益' }
                }
              }
            }
          }
        }
      },
      required: ['code', 'message', 'data']
    },
    
    // 通用API响应（用于未特别定义的接口）
    ApiResponse: {
      type: 'object',
      properties: {
        code: {
          type: 'integer',
          description: '响应状态码',
          example: 200
        },
        message: {
          type: 'string',
          description: '响应消息',
          example: '操作成功'
        },
        data: {
          type: 'object',
          description: '响应数据，具体结构根据不同接口而定，包含统计分析结果、图表数据、排行榜等信息'
        }
      },
      required: ['code', 'message', 'data']
    },
    
    ErrorResponse: {
      type: 'object',
      properties: {
        code: {
          type: 'integer',
          example: 500
        },
        message: {
          type: 'string',
          example: '服务器内部错误'
        }
      }
    }
  };
}



// OpenAPI文档模板
const openApiTemplate = {
  openapi: '3.0.0',
  info: {
    title: '智能问数API',
    description: 'API接口文档，包含高价值商品、资产管理和房屋管理三大模块',
    version: '1.0.0',
    contact: {
      name: 'API Support',
      email: 'support@hnlg.com'
    }
  },
  servers: [
    {
      url: 'http://localhost:3010',
      description: '开发环境'
    },
    {
      url: 'https://api.hnlg.com',
      description: '生产环境'
    }
  ],
  tags: [
    {
      name: '高价值商品管理',
      description: '高价值商品的统计分析和管理功能'
    },
    {
      name: '资产管理',
      description: '资产的统计分析和管理功能'
    },
    {
      name: '房屋管理',
      description: '房屋的统计分析和管理功能'
    }
  ],
  paths: {},
  components: {
    schemas: createDetailedSchemas()
  }
};

/**
 * 从文件内容中提取Swagger注释
 * @param {string} content - 文件内容
 * @param {string} filePath - 文件路径
 * @returns {Object|null} - 提取的API信息
 */
function extractSwaggerFromFile(content, filePath) {
  const swaggerRegex = /\/\*\*[\s\S]*?@swagger[\s\S]*?\*\//g;
  const matches = content.match(swaggerRegex);
  
  if (!matches || matches.length === 0) {
    return null;
  }

  try {
    // 提取路径信息
    const relativePath = path.relative(config.apiDir, filePath);
    const apiPath = '/api/' + relativePath.replace(/\.js$/, '').replace(/\\/g, '/');
    
    // 简单的注释解析（实际项目中可能需要更复杂的解析器）
    const comment = matches[0];
    
    // 提取标签
    const tagMatch = comment.match(/tags:\s*\n\s*-\s*(.+)/i);
    let tag = tagMatch ? tagMatch[1].trim() : '其他';
    
    // 如果没有找到标签，根据路径推断模块
    if (tag === '其他') {
      if (apiPath.includes('/high-goods/')) {
        tag = '高价值商品管理';
      } else if (apiPath.includes('/asset/')) {
        tag = '资产管理';
      } else if (apiPath.includes('/room/')) {
        tag = '房屋管理';
      }
    }
    
    // 提取摘要
    const summaryMatch = comment.match(/summary:\s*(.+)/i);
    const summary = summaryMatch ? summaryMatch[1].trim() : '接口描述';
    
    // 提取描述
    const descMatch = comment.match(/description:\s*(.+)/i);
    const description = descMatch ? descMatch[1].trim() : summary;
    
    // 提取参数
    const parameters = [];
    const parameterRegex = /parameters:[\s\S]*?(?=responses:|$)/i;
    const parameterSection = comment.match(parameterRegex);
    
    if (parameterSection) {
      const paramLines = parameterSection[0].split('\n');
      let currentParam = null;
      
      for (const line of paramLines) {
        // 去掉JSDoc注释的*前缀
        const cleanLine = line.replace(/^\s*\*\s*/, '').trim();
        
        // 检测参数开始
        const paramMatch = cleanLine.match(/^-\s*in:\s*(\w+)/);
        if (paramMatch) {
          if (currentParam) {
            parameters.push(currentParam);
          }
          currentParam = {
            in: paramMatch[1],
            schema: { type: 'string' }
          };
          continue;
        }
        
        if (currentParam) {
          // 提取参数名
          const nameMatch = cleanLine.match(/name:\s*(.+)/);
          if (nameMatch) {
            currentParam.name = nameMatch[1].trim();
            continue;
          }
          
          // 提取参数类型
          const typeMatch = cleanLine.match(/type:\s*(\w+)/);
          if (typeMatch) {
            currentParam.schema.type = typeMatch[1];
            continue;
          }
          
          // 提取参数格式
          const formatMatch = cleanLine.match(/format:\s*(\w+)/);
          if (formatMatch) {
            currentParam.schema.format = formatMatch[1];
            continue;
          }
          
          // 提取参数描述
          const descriptionMatch = cleanLine.match(/description:\s*(.+)/);
          if (descriptionMatch) {
            currentParam.description = descriptionMatch[1].trim();
            continue;
          }
        }
      }
      
      // 添加最后一个参数
      if (currentParam) {
        parameters.push(currentParam);
      }
      

    }
    
    // 提取响应schema
    const responses = extractResponseSchema(comment, filePath);
    
    const apiSpec = {
      path: apiPath,
      method: 'get', // 默认GET方法
      tag,
      summary,
      description,
      responses: responses || {
        '200': {
          description: '成功',
          content: {
            'application/json': {
              schema: {
                $ref: '#/components/schemas/ApiResponse'
              }
            }
          }
        },
        '500': {
          description: '服务器内部错误',
          content: {
            'application/json': {
              schema: {
                $ref: '#/components/schemas/ErrorResponse'
              }
            }
          }
        }
      }
    };
    
    // 如果有参数，添加到API规范中
    if (parameters.length > 0) {
      apiSpec.parameters = parameters;
    }
    
    return apiSpec;
  } catch (error) {
    console.warn(`解析文件 ${filePath} 时出错:`, error.message);
    return null;
  }
}

/**
 * 扫描API目录并生成文档
 */
function generateDocs() {
  console.log('开始生成API文档...');
  
  // 查找所有API文件
  const apiFiles = glob.sync('**/*.js', {
    cwd: config.apiDir,
    ignore: ['**/index.js'] // 忽略索引文件
  });
  
  console.log(`找到 ${apiFiles.length} 个API文件`);
  
  const openApiDoc = JSON.parse(JSON.stringify(openApiTemplate));
  
  // 处理每个API文件
  apiFiles.forEach(file => {
    const filePath = path.join(config.apiDir, file);
    
    try {
      const content = fs.readFileSync(filePath, 'utf8');
      const apiInfo = extractSwaggerFromFile(content, filePath);
      
      if (apiInfo) {
        // 添加到OpenAPI文档
        if (!openApiDoc.paths[apiInfo.path]) {
          openApiDoc.paths[apiInfo.path] = {};
        }
        
        const methodSpec = {
          tags: [apiInfo.tag],
          summary: apiInfo.summary,
          description: apiInfo.description,
          responses: apiInfo.responses
        };
        
        // 如果有参数，添加到方法规范中
        if (apiInfo.parameters && apiInfo.parameters.length > 0) {
          methodSpec.parameters = apiInfo.parameters;
        }
        
        openApiDoc.paths[apiInfo.path][apiInfo.method] = methodSpec;
        
        console.log(`✓ 处理文件: ${file} -> ${apiInfo.path}`);
      } else {
        console.log(`⚠ 跳过文件: ${file} (未找到Swagger注释)`);
      }
    } catch (error) {
      console.error(`✗ 处理文件 ${file} 时出错:`, error.message);
    }
  });
  
  // 确保输出目录存在
  const outputDir = path.dirname(config.outputFile);
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }
  
  // 写入文档文件
  fs.writeFileSync(config.outputFile, JSON.stringify(openApiDoc, null, 2), 'utf8');
  
  console.log(`\n✓ API文档已生成: ${config.outputFile}`);
  console.log(`✓ 共处理 ${Object.keys(openApiDoc.paths).length} 个API接口`);
  
  // 生成统计信息
  const stats = {};
  Object.values(openApiDoc.paths).forEach(pathObj => {
    Object.values(pathObj).forEach(methodObj => {
      if (methodObj.tags && methodObj.tags[0]) {
        const tag = methodObj.tags[0];
        stats[tag] = (stats[tag] || 0) + 1;
      }
    });
  });
  
  console.log('\n📊 接口统计:');
  Object.entries(stats).forEach(([tag, count]) => {
    console.log(`  ${tag}: ${count} 个接口`);
  });
}

/**
 * 监听文件变化并自动重新生成文档
 */
function watchFiles() {
  console.log('\n👀 开始监听文件变化...');
  
  const chokidar = require('chokidar');
  const watcher = chokidar.watch(config.apiDir + '/**/*.js', {
    ignored: /node_modules/,
    persistent: true
  });
  
  watcher.on('change', (filePath) => {
    console.log(`\n📝 文件变化: ${path.relative(process.cwd(), filePath)}`);
    generateDocs();
  });
  
  watcher.on('add', (filePath) => {
    console.log(`\n➕ 新增文件: ${path.relative(process.cwd(), filePath)}`);
    generateDocs();
  });
  
  watcher.on('unlink', (filePath) => {
    console.log(`\n🗑️ 删除文件: ${path.relative(process.cwd(), filePath)}`);
    generateDocs();
  });
}

// 主函数
function main() {
  const args = process.argv.slice(2);
  
  if (args.includes('--watch') || args.includes('-w')) {
    generateDocs();
    watchFiles();
  } else {
    generateDocs();
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}

module.exports = {
  generateDocs,
  watchFiles,
  config,
  extractSchemasFromFiles,
  extractSchemaFromSwagger
};